import webviews from '../webviews.js';
import { db } from '../util/database.js';
import Tooltip from '@mui/material/Tooltip';
import SearchBar from './searchbar/searchbar.js';
import Findinpage from "./findinpage"
import DownloadManager from '../../DownloadManager';
import WindowControls from '../WindowControls.js';
import ErrUi from '../../ErrUi';
import PasswordViewer from '../passwordManager/PasswordViewer.js';
import IconButton from '@mui/material/IconButton';
import MenuIcon from '@mui/icons-material/Menu';
import BackIcon from '@mui/icons-material/ArrowBack';
import ForwardIcon from '@mui/icons-material/ArrowForward';
import PanToolIcon from '@mui/icons-material/PanTool';
import AddIcon from '@mui/icons-material/Add';
import Toolbar from '@mui/material/Toolbar';
import AppBar from '@mui/material/AppBar';
import Tab from '@mui/material/Tab';
import Tabs from '@mui/material/Tabs';
import KeyboardDoubleArrowDownIcon from '@mui/icons-material/KeyboardDoubleArrowDown';
import MySetting from '../../MySetting';
import PasswordCapture from '../passwordManager/PasswordCapture.js';
import * as store from '../../reducers/partsSlice';
import React from 'react';
import BookMark from '../../BookMark';
import History from '../../History';
const ipc = window.require('electron').ipcRenderer;
function TabEle(props) {
  const onclick = (e) => {
    props.onClick(props.key);
  };

  const onauxclick = (e) => {
    if (e.button === 1) {
      // if mouse middle click -> close tab
      props.tab_closed(props.tab.id);
    }
  };
  const onwheel = (e) => { };

  let tabTitle_content = (props.tab.title || l('newTabLabel')).substring(
    0,
    500
  );
  let title = tabTitle_content;
  if (props.tab.private) {
    title += ' (' + l('privateTab') + ')';
  }

  return (
    <Tab style={{ height: "32px", overflow: "hidden" }}
      onAuxClick={onauxclick}
      onClick={onclick}
      onWheel={onwheel}
      key={props.key}
      data-tab={props.tab.id}
      role="tab"
      label={tabTitle_content}
    ></Tab>
  );
}
export default class TabBar extends React.Component {
  constructor(props) {
    super();
    this.ref_menuButton = React.createRef();
  }
  componentDidMount = () => {
    // this.changed = false;
  };
  // update_goback = () => {

  // };
  showSecondaryMenu = () => {
    var rect = this.ref_menuButton.current.getBoundingClientRect();
    ipc.send('showSecondaryMenu', {
      x: Math.round(rect.left),
      y: Math.round(rect.bottom),
    });
  };
  tab_click = (key) => {
    if (this.props.state.tab_value !== key) {
      this.props.dispatch(store.partsSlice.actions.SWITCH_TAB(key));
    } else {
      this.toEdit(this.props.state.tabs[key].id);
    }

  }
  toEdit = (tabid) => {
    this.props.dispatch(store.partsSlice.actions.TOGGLE_DROP());
  };
  render() {
    // console.log('tabBar=====================================');
    var state = this.props.state;
    // console.log("TabBar----------------")
    // console.log(state.tabs);
    // const dispatch = useDispatch();
    const show_drop_state = state.show_drop;
    const show_search = state.show_search;
    var tabs = state.tabs;
    var tab_value = state.tab_value;
    // console.log(state);
    let tabeles = [];
    let tabpanels = [];
    let key;
    let i;
    for (i = 0; i < tabs.length; i++) {
      tabeles.push(
        TabEle({
          key: i,
          onClick: this.tab_click,
          tab: tabs[i],
        })
      );
    }
    return (
      <div style={{ display: 'flex', flexDirection: 'column' }}>
        <AppBar position="static">
          <Toolbar variant="dense">
            <IconButton  style={{"WebkitAppRegion":"drag"}}>
             <PanToolIcon />
            </IconButton>
            <IconButton
              ref={this.ref_menuButton}
              onClick={() => {
                this.showSecondaryMenu();
              }}
            >
              <MenuIcon />
            </IconButton>
            <IconButton
              onClick={() => {
                this.props.dispatch(store.partsSlice.actions.TOGGLE_DROP());
              }}
            >
              <KeyboardDoubleArrowDownIcon />
            </IconButton>
            <IconButton
              disabled={state.goback_disabled}
              onClick={() => {
                webviews.goBackIgnoringRedirects(
                  this.props.state.tabs[this.props.state.tab_value].id
                );
              }}
              id="back-button"
              data-label="goBack"
            >
              <BackIcon />
            </IconButton>
            <IconButton
              onClick={() => {
                webviews.callAsync(
                  this.props.state.tabs[this.props.state.tab_value].id,
                  'goForward'
                );
              }}
              id="forward-button"
              data-label="goForward"
              disabled={state.goforward_disabled}
            >
              <ForwardIcon />
            </IconButton>
            <div style={{ flex: "1" }}>
              <Tabs variant="scrollable"
                scrollButtons
                allowScrollButtonsMobile
                aria-label="scrollable force tabs example"
                onChange={(event, value) => {
                  this.props.dispatch(store.partsSlice.actions.TAB_VALUE(value));
                }}
                value={state.tab_value}
              >
                {tabeles}
              </Tabs>
            </div>
            <Tooltip title="add tab" placement="left">
              <IconButton
                onClick={() => {
                  this.props.dispatch(store.partsSlice.actions.ADD_TAB({}));
                }}
                id="add-tab-button"
                className="navbar-action-button i carbon:add"
                data-label="newTabAction"
              >
                <AddIcon />
              </IconButton>
            </Tooltip>
            <WindowControls />
          </Toolbar>
        </AppBar>
        <div
          style={{
            display: show_drop_state ? 'flex' : 'none',
            flexDirection: 'column',
          }}
        >
          <SearchBar state={this.props.state} dispatch={this.props.dispatch} hidden={!this.props.state.show_search} />
          {this.props.state.show_history ? <History /> : null}
          {this.props.state.show_setting ? <MySetting /> : null}
          {this.props.state.show_find ? <Findinpage state={this.props.state} dispatch={this.props.dispatch} /> : null}
          {this.props.state.show_download ? <DownloadManager /> : null}
          {this.props.state.show_pwdview ? <PasswordViewer /> : null}
          <PasswordCapture state={this.props.state} dispatch={this.props.dispatch} />
          {this.props.state.show_book ? <BookMark /> : null}
          {this.props.state.show_error ? <ErrUi /> : null}
        </div>
      </div>
    );
  }
}
